package com.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.entity.SysMenu;
import com.rbac.mapper.SysMenuMapper;
import com.rbac.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 菜单服务实现类
 *
 * @author rbac-system
 * @since 2024-01-01
 */
@Service
@Transactional
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Override
    public IPage<SysMenu> page(IPage<SysMenu> page, String menuName, String menuCode, Integer menuType, Integer status) {
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(menuName), SysMenu::getMenuName, menuName)
               .like(StringUtils.hasText(menuCode), SysMenu::getMenuCode, menuCode)
               .eq(menuType != null, SysMenu::getMenuType, menuType)
               .eq(status != null, SysMenu::getStatus, status)
               .orderByAsc(SysMenu::getSortOrder)
               .orderByDesc(SysMenu::getCreateTime);
        return page(page, wrapper);
    }

    @Override
    public List<SysMenu> getMenuTree() {
        return baseMapper.selectMenuTree();
    }

    @Override
    public List<SysMenu> getMenusByRoleId(Long roleId) {
        return baseMapper.selectMenusByRoleId(roleId);
    }

    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        return baseMapper.selectMenusByUserId(userId);
    }

    @Override
    public boolean existsByMenuCode(String menuCode) {
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysMenu::getMenuCode, menuCode);
        return count(wrapper) > 0;
    }

    @Override
    public boolean existsByMenuCodeAndIdNot(String menuCode, Long id) {
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysMenu::getMenuCode, menuCode)
               .ne(SysMenu::getId, id);
        return count(wrapper) > 0;
    }
}
